package com.macbulldev.poc.testgin.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;


import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.service.WebappUtils;
import com.macbulldev.poc.testgin.domain.AppRole;
import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.jobs.UserRequestNotificationJob;


@org.springframework.stereotype.Controller
public class AppUserRequestController {
private static final Logger LOGGER = Logger.getLogger(AppUserRequestController.class);

//
//@Autowired
//@Qualifier("schedulerFactory")
//private SchedulerFactoryBean schedulerFactory;


@RequestMapping(value = "/appuser_request", method = RequestMethod.GET)    
public String renderUserRequestForm(Model model) {    

	 model.addAttribute("appUser", new AppUser());
	 model.addAttribute("availableRoles",AppRole.findAllUnassociatedRoles());
	 return "appuser/request";   
}


@RequestMapping(value = "/appuser_request", method = RequestMethod.POST)    
public String requestUser(Model model,
		@Valid @ModelAttribute("appUser") AppUser appUser,
		BindingResult result, HttpSession session) {
	
		LOGGER.error("Create User.........");
	
    	if (appUser == null) throw new IllegalArgumentException("A appUser is required");        
    	if (!appUser.getPassword().equals(appUser.getConfirmPassword()))
		{
			result.addError(new FieldError("appUser","confirmPassword","Password Match Failed"));
		}
    	if (!result.hasErrors()) 
    	{
    			
    			LOGGER.error("No Errors Create User......");
    			
    		
    		
    			appUser.setIsEnabled(false);
    			appUser.setIsApproved(false);
    			appUser.setCreateTs(new Date());

    			if (appUser.getFaxNumber().trim().length()==0)
    			{
    				appUser.setFaxNumber(null);
    			}
    			
    			appUser.persist();   
    			
    			EventLog log = new EventLog();
    	        log.setCreateTs(new Date());
    	        log.setCreateUsername(appUser.getEmail());

    	        log.setObjectClass(AppUser.class.getSimpleName());
    	        log.setOperation("User "+appUser.getEmail()+" requested");
    	        log.persist();
    	    		
//    			try
//    			{
//    			Scheduler sched = schedulerFactory.getScheduler();
//    	    	JobDetail jobDetail = new JobDetail(new Date().getTime()+Math.random()+"","default",UserRequestNotificationJob.class);
//    	    	
//    	    	JobDataMap jobData =  new JobDataMap();
//    	    	jobData.put(UserRequestNotificationJob.USER_OBJ_KEY, appUser);
//    	    	
//    	    	jobDetail.setJobDataMap(jobData);
//    	    	
//    	    	Date now = new Date();
//    	    	Trigger trigger = TriggerUtils.makeImmediateTrigger(0, 0);
//    	    	trigger.setStartTime(now);
//    	    	trigger.setName(Long.toString(now.getTime()));
//    	    	
//    	    	sched.scheduleJob(jobDetail, trigger);
//    			}
//    			catch (Exception e)
//    			{
//    				LOGGER.error("Exception caught scheduling admin notificaiton.  Ignoring and movin on",e);
//    			}
    			return "appuser/request_success";      
    		
    	}        

    	model.addAttribute("appUser", appUser);            
    	model.addAttribute("appUser_createTs_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));            

    return "appuser/request";  
}

//
//public SchedulerFactoryBean getSchedulerFactory() {
//	return schedulerFactory;
//}
//
//
//public void setSchedulerFactory(SchedulerFactoryBean schedulerFactory) {
//	this.schedulerFactory = schedulerFactory;
//}


}
